package com.yc.thread.lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class TestCyclicBarrier {
	
	CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> System.out.println("人到齐了"));
	
	public void m1() {
		for (int i = 0; i < 5; i++) {
			try {
				System.out.println(cyclicBarrier.getNumberWaiting());
				cyclicBarrier.await();
				
			} catch (InterruptedException | BrokenBarrierException e) {
				e.printStackTrace();
			}
		}
		System.out.println("----------over");
	}
	
	public void m2() {
		for (int i = 0; i < 15; i++) {
			System.out.println(cyclicBarrier.getNumberWaiting());
			new Thread(new myRunable()).start();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		System.out.println("--------game--over");
	}

	public static void main(String[] args) {
		
		TestCyclicBarrier tb = new TestCyclicBarrier();
//		tb.m1();
		
		tb.m2();
	}
	
	class myRunable implements Runnable {

		@Override
		public void run() {
			try {
				
				cyclicBarrier.await();
				System.out.println(Thread.currentThread().getName() + "执行完毕");
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
			
		}
		
	}

}
